# -------------------------------------------------------------------
#       -*- coding: utf-8 -*-
#   @Project    :   spider
#   @File       :   47_异步http请求aiohttp模块.py
#   @Author     :   WANGYU
#   @Time       :   2021-09-04 10:24:30
#   @Software   :   PyCharm
#   @Desc       :   
# -------------------------------------------------------------------


# requests.get()同步的代码 换成 异步操作aiohttp
import aiohttp
import asyncio

urls = [
    'http://kr.shanghai-jiuxin.com/file/2020/1031/191468637cab2f0206f7d1d9b175ac81.jpg',
    'http://kr.shanghai-jiuxin.com/file/2020/1031/563337d07af599a9ea64e620729f367e.jpg',
    'http://kr.shanghai-jiuxin.com/file/2020/1031/774218be86d832f359637ab120eba52d.jpg'
]


async def aiodownload(url):
    # 发送请求
    # s = aiohttp.ClientSession() 等价于 requests
    # 得到图片内容
    # 保存到文件
    name = url.rsplit('/', 1)[1]  # 从右边切一次，得到第一个位置内容
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            # 请求回来，写入文件
            with open('./img/' + name, mode='wb') as f:
                f.write(await resp.content.read())  # 读取内容是异步的需要挂起,返回内容用resp.content,返回页面源代码用resp.text
    print('搞定', name)


async def main():
    tasks = []
    for url in urls:
        tasks.append(aiodownload(url))
    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main())
